/*
 * @Author: xushuhao
 * @Email: xshmouse@163.com
 * @Date: 2020-04-19 21:47:40
 * @Last Modified by: xushuhao
 * @Last Modified time: 2020-06-24 11:29:30
 * @Description: 基类（base_widget)扩展功能库
 */

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_code_framework/utils/global.dart';
import 'package:flutter_sfsymbols/flutter_sfsymbols.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import 'package:provider/single_child_widget.dart';

/// base 类 常用的一些工具类 ， 放在这里就可以了
abstract class BaseFuntion {
  State _stateBaseFunction;
  BuildContext _contextBaseFunction;

  bool isDark; //是否暗黑模式

  bool _isAppTopNavBarShow = false; //头部导航栏是否显示

  IconData _topNavLeftIcon = SFSymbols.chevron_left;

  bool _isErrorWidgetShow = false; //错误信息是否显示

  //Scaffold bottomNavigationBar 时设置高度 kBottomNavigationBarHeight
  ////自定义Tabbar高度  56
  double kTabbarHeigt = kBottomNavigationBarHeight + 20;

  Color _apptabBarColor;
  Color _appTopNavBarColor; //顶部导航栏
  Color _appBarContentColor;
  Color _appMainColor;
  Color _appAccentColor;

  String _appBarTitle;
  String _appBarRightTitle = "";

  String _topNavTitle = ""; //顶部导航栏标题文字

  String _errorContentMesage = "网络错误啦~~~";

  String _errImgPath = "lib/assets/images/base/error.png";

  bool _isLoadingWidgetShow = false;

  bool _isEmptyWidgetVisible = false;

  String _emptyWidgetContent = "暂无数据~";

  String _emptyImgPath = "lib/assets/images/base/empty.png";

  Color _baseFunWidgetBackground = Colors.grey[100];

  bool _isBackIconShow = true;

  FontWeight _fontWidget = FontWeight.w600; //错误页面和空页面的字体粗度

  double bottomVsrtical = 0; //作为内部页面距离底部的高度

  void initBaseCommon(State state) {
    _stateBaseFunction = state;
    _contextBaseFunction = state.context;
    _appBarTitle = getWidgetName();

    /////////////////ListView////////////////////

    _controller.addListener(() {
      var maxScroll = _controller.position.maxScrollExtent;
      var pixels = _controller.position.pixels;
      print('maxscroll = ' +
          maxScroll.toString() +
          'current pix = ' +
          pixels.toString());
      if (maxScroll == pixels) {
        //上拉刷新做处理
        print('load more ...');
        //curPage++;
        //改变数据，这里随意发挥
        initData(true);
      }
    });
    /////////////////////////////////////

    /// Listview 滑块抽屉
    slidableController = SlidableController(
      onSlideAnimationChanged: handleSlideAnimationChanged,
      // onSlideIsOpenChanged: handleSlideIsOpenChanged,
    );

    ///
  }

  void initTheme() {
    _appMainColor = Theme.of(_contextBaseFunction).primaryColor;
    _apptabBarColor = Theme.of(_contextBaseFunction).backgroundColor;
    _appTopNavBarColor = Theme.of(_contextBaseFunction).backgroundColor; //顶部导航栏
    _appBarContentColor = Theme.of(_contextBaseFunction).backgroundColor;
    _appAccentColor = Theme.of(_contextBaseFunction).accentColor;
  }

  Future<bool> willPop() {
    return new Future.value(true);
  }

  //项部导航左箭头返回
  topNavPop(){
    Navigator.of(_contextBaseFunction).pop();
  }

  Widget getBaseView(BuildContext context) {
    // print('get Base  ');
    return Stack(
        children: <Widget>[
          SafeArea(
            child: Column(
              children: <Widget>[
                _isAppTopNavBarShow ? _getAppTopNagBar() : _getHolderLWidget(),
                Container(
                  width: getScreenWidth(),
                  height: getMainWidgetHeight(),
                  color: Theme.of(context).backgroundColor,
                  child: Stack(
                    children: <Widget>[
                      _buildProviderWidget(context),
                      _isErrorWidgetShow
                          ? _getBaseErrorWidget()
                          : _getHolderLWidget(),
                      _isEmptyWidgetVisible
                          ? _getBaseEmptyWidget()
                          : _getHolderLWidget(),
                      _isLoadingWidgetShow
                          ? _getBassLoadingWidget()
                          : _getHolderLWidget(),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ],
      
    );
  }

  Widget _getHolderLWidget() {
    return Container(
      width: 0,
      height: 0,
    );
  }

  Widget _getBaseTabBar() {
    //getTabBarCupertinoView(context); //getTabBar(context);
    //自定义Tabbar时使用，目前使用Scaffold bottomNavigationBar 暂时停用。
    return Container(
      width: 0,
      height: 0,
    );
  }

  Widget _getAppTopNagBar() {
    return getAppTopNagBar();
  }

  ///设置状态栏，可以自行重写拓展成其他的任何形式
  Widget getTabBar() {
    return Container(
      height: kTabbarHeigt,
      width: double.infinity,
      color: _apptabBarColor,
      child: Text('ddddddddd'),
    );
  }

  ///暴露的错误页面方法，可以自己重写定制
  Widget getErrorWidget() {
    return Container(
      //错误页面中心可以自己调整
      padding: EdgeInsets.fromLTRB(0, 0, 0, 200),
      color: _baseFunWidgetBackground,
      width: double.infinity,
      height: double.infinity,
      child: Center(
        child: InkWell(
          onTap: onClickErrorWidget,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Image(
                image: AssetImage(_errImgPath),
                width: 150,
                height: 150,
              ),
              Container(
                margin: EdgeInsets.fromLTRB(0, 10, 0, 0),
                child: Text(_errorContentMesage,
                    style: TextStyle(
                      fontWeight: _fontWidget,
                    )),
              ),
            ],
          ),
        ),
      ),
    );
  }

  ///点击错误页面后展示内容
  void onClickErrorWidget() {
    log('error try');
    onResume(); //此处 默认onResume 就是 调用网络请求，
  }

  Widget getLoadingWidget() {
    return Container(
      //错误页面中心可以自己调整
      padding: EdgeInsets.fromLTRB(0, 0, 0, 100),
      color: Color.fromRGBO(242, 242, 242, 0.5),
      width: double.infinity,
      height: double.infinity,
      child: Center(
        child:
            // 圆形进度条
            CircularProgressIndicator(
          strokeWidth: 4.0,
          backgroundColor: _appMainColor,
          // value: 0.2,
          valueColor: AlwaysStoppedAnimation<Color>(_appAccentColor),
        ),
      ),
    );
  }

  void clickAppBarBack() {
    finish();
  }

  void finish<T extends Object>([T result]) {
    if (Navigator.canPop(_contextBaseFunction)) {
      Navigator.pop<T>(_contextBaseFunction, result);
    } else {
      //说明已经没法回退了 ， 可以关闭了
      finishDartPageOrApp();
    }
  }

//
//
//  defaultRouteName → String 启动应用程序时嵌入器请求的路由或路径。
//  devicePixelRatio → double 每个逻辑像素的设备像素数。 例如，Nexus 6的设备像素比为3.5。
//  textScaleFactor → double 系统设置的文本比例。默认1.0
//  toString（） → String 返回此对象的字符串表示形式。
//  physicalSize → Size 返回一个包含屏幕宽高的对象，单位是dp
//
//

  ///返回中间可绘制区域，也就是 我们子类 buildWidget 可利用的空间高度
  double getMainWidgetHeight() {
    //此处在SafeArea内,所以减去top、bottom pad
    double screenHeight = getScreenHeight() -
        getTopSafeHeight() -
        getBottomSafeHeight() -
        bottomVsrtical;

    if (_isAppTopNavBarShow) {
      screenHeight = screenHeight - getAppBarHeight();
    }

    return screenHeight;
  }

  ///返回屏幕高度
  double getScreenHeight() {
    return MediaQuery.of(_contextBaseFunction).size.height;
  }

  ///返回状态栏、顶部安全高度
  double getTopSafeHeight() {
    return MediaQuery.of(_contextBaseFunction).padding.top;
  }

  ///返回底部安全高度
  double getBottomSafeHeight() {
    return MediaQuery.of(_contextBaseFunction).padding.bottom;
  }

//返回自定义Tabbar 高度。
  double getTabBarHeight() {
    return kTabbarHeigt;
  }

  ///返回appbar高度，也就是导航栏高度
  double getAppBarHeight() {
    return kToolbarHeight;
  }

  ///返回屏幕宽度
  double getScreenWidth() {
    return MediaQuery.of(_contextBaseFunction).size.width;
  }

  Widget _getBaseErrorWidget() {
    return getErrorWidget();
  }

  Widget _getBassLoadingWidget() {
    return getLoadingWidget();
  }

  Widget _getBaseEmptyWidget() {
    return getEmptyWidget();
  }

  Widget getEmptyWidget() {
    return Container(
      //错误页面中心可以自己调整
      padding: EdgeInsets.fromLTRB(0, 0, 0, 200),
      color: _baseFunWidgetBackground,
      width: double.infinity,
      height: double.infinity,
      child: Center(
        child: Container(
          alignment: Alignment.center,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Image(
                image: AssetImage(_emptyImgPath),
                width: 150,
                height: 150,
              ),
              Container(
                margin: EdgeInsets.fromLTRB(0, 10, 0, 0),
                child: Text(_emptyWidgetContent,
                    style: TextStyle(
                      fontWeight: _fontWidget,
                    )),
              )
            ],
          ),
        ),
      ),
    );
  }

  ///关闭最后一个 flutter 页面 ， 如果是原生跳过来的则回到原生，否则关闭app
  void finishDartPageOrApp() {
    SystemNavigator.pop();
  }

  ///导航栏 顶部导航
  Widget getAppTopNagBar(){
    return Container(
      height: 44, //getAppBarHeight(),
      width: double.infinity,
      color: _appTopNavBarColor, // _appTopNavBarColor Colors.pink[200],
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          GestureDetector(
            child: Container(
                padding: EdgeInsets.fromLTRB(24, 0, 10, 0),
                color: Theme.of(_contextBaseFunction).backgroundColor,
                child: Icon(
                  _topNavLeftIcon,
                  size: 21,
                  color: Theme.of(_contextBaseFunction)
                      .primaryTextTheme
                      .headline2
                      .color,
                )),
            onTap: () {
              //Navigator.of(_contextBaseFunction).pop();
              topNavPop();
            },
          ),
          Expanded(
              child: Center(
            child: Text(_topNavTitle,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                    fontSize: 18,
                    color: Theme.of(_contextBaseFunction)
                        .primaryTextTheme
                        .headline2
                        .color)),
          )),
          Container(
            padding: EdgeInsets.fromLTRB(10, 0, 24, 0),
            child: getTopNavRightWidget(_contextBaseFunction),
          ),
        ],
      ),
    );
  }

  //返回Top导航栏 Text
  void setTopNavTitle(String title) {
    if (_stateBaseFunction != null && _stateBaseFunction.mounted) {
      _stateBaseFunction.setState(() {
        _topNavTitle = title;
      });
    }
  }

  /// 默认返回
  /// 关闭 SFSymbols.xmark
  void setTopNavLeftIcon(IconData icon) {
    if (_stateBaseFunction != null && _stateBaseFunction.mounted) {
      _stateBaseFunction.setState(() {
        _topNavLeftIcon = icon;
      });
    }
  }

  //顶部导航右侧控件 子类中实现
  Widget getTopNavRightWidget(BuildContext _contextBaseFunction) {
    return Text('');
  }

  ///默认这个状态栏下，设置颜色
  void setTopBarBackColor(Color color) {
    // ignore: invalid_use_of_protected_member
    if (_stateBaseFunction != null && _stateBaseFunction.mounted) {
      _stateBaseFunction.setState(() {
        _apptabBarColor = color == null ? _apptabBarColor : color;
      });
    }
  }

  ///设置导航栏的字体以及图标颜色
  void setAppBarContentColor(Color contentColor) {
    if (contentColor != null) {
      if (_stateBaseFunction != null && _stateBaseFunction.mounted) {
        // ignore: invalid_use_of_protected_member
        _stateBaseFunction.setState(() {
          _appBarContentColor = contentColor;
        });
      }
    }
  }

  ///设置导航栏隐藏或者显示
  void setAppTopNavBarVisible(bool isVisible) {
    // ignore: invalid_use_of_protected_member
    if (_stateBaseFunction != null && _stateBaseFunction.mounted) {
      _stateBaseFunction.setState(() {
        _isAppTopNavBarShow = isVisible;
      });
    }
  }

  ///默认这个导航栏下，设置颜色
  void setAppTopNavBarBackColor(Color color) {
    // ignore: invalid_use_of_protected_member
    if (_stateBaseFunction != null && _stateBaseFunction.mounted) {
      _stateBaseFunction.setState(() {
        _appTopNavBarColor = color == null ? _appTopNavBarColor : color;
      });
    }
  }

  void setAppBarTitle(String title) {
    if (title != null) {
      if (_stateBaseFunction != null && _stateBaseFunction.mounted) {
        // ignore: invalid_use_of_protected_member
        _stateBaseFunction.setState(() {
          _appBarTitle = title;
        });
      }
    }
  }

  void setAppBarRightTitle(String title) {
    if (title != null) {
      if (_stateBaseFunction != null && _stateBaseFunction.mounted) {
        // ignore: invalid_use_of_protected_member
        _stateBaseFunction.setState(() {
          _appBarRightTitle = title;
        });
      }
    }
  }

  ///设置错误提示信息
  void setErrorContent(String content) {
    if (content != null) {
      if (_stateBaseFunction != null && _stateBaseFunction.mounted) {
        // ignore: invalid_use_of_protected_member
        _stateBaseFunction.setState(() {
          _errorContentMesage = content;
        });
      }
    }
  }

  ///设置错误页面显示或者隐藏
  void setErrorWidgetVisible(bool isVisible) {
    // ignore: invalid_use_of_protected_member
    if (_stateBaseFunction != null && _stateBaseFunction.mounted) {
      _stateBaseFunction.setState(() {
        if (isVisible) {
          //如果可见 说明 空页面要关闭啦
          _isEmptyWidgetVisible = false;
        }
        // 不管如何loading页面要关闭啦，
        _isLoadingWidgetShow = false;
        _isErrorWidgetShow = isVisible;
      });
    }
  }

  ///设置空页面显示或者隐藏
  void setEmptyWidgetVisible(bool isVisible) {
    // ignore: invalid_use_of_protected_member
    if (_stateBaseFunction != null && _stateBaseFunction.mounted) {
      _stateBaseFunction.setState(() {
        if (isVisible) {
          //如果可见 说明 错误页面要关闭啦
          _isErrorWidgetShow = false;
        }

        // 不管如何loading页面要关闭啦，
        _isLoadingWidgetShow = false;
        _isEmptyWidgetVisible = isVisible;
      });
    }
  }

  void setLoadingWidgetVisible(bool isVisible) {
    // ignore: invalid_use_of_protected_member
    if (_stateBaseFunction != null && _stateBaseFunction.mounted) {
      _stateBaseFunction.setState(() {
        _isLoadingWidgetShow = isVisible;
      });
    }
  }

  ///设置空页面内容
  void setEmptyWidgetContent(String content) {
    if (content != null) {
      if (_stateBaseFunction != null && _stateBaseFunction.mounted) {
        // ignore: invalid_use_of_protected_member
        _stateBaseFunction.setState(() {
          _emptyWidgetContent = content;
        });
      }
    }
  }

  ///设置错误页面图片
  void setErrorImage(String imagePath) {
    if (imagePath != null) {
      if (_stateBaseFunction != null && _stateBaseFunction.mounted) {
        // ignore: invalid_use_of_protected_member
        _stateBaseFunction.setState(() {
          _errImgPath = imagePath;
        });
      }
    }
  }

  ///设置空页面图片
  void setEmptyImage(String imagePath) {
    if (imagePath != null) {
      if (_stateBaseFunction != null && _stateBaseFunction.mounted) {
        // ignore: invalid_use_of_protected_member
        _stateBaseFunction.setState(() {
          _emptyImgPath = imagePath;
        });
      }
    }
  }

  void setBackIconHinde({bool isHiinde = true}) {
    // ignore: invalid_use_of_protected_member
    if (_stateBaseFunction != null && _stateBaseFunction.mounted) {
      _stateBaseFunction.setState(() {
        _isBackIconShow = !isHiinde;
      });
    }
  }

  ///初始化一些变量 相当于 onCreate ， 放一下 初始化数据操作
  void onCreate();

  ///相当于onResume, 只要页面来到栈顶， 都会调用此方法，网络请求可以放在这个方法
  void onResume();

  ///页面被覆盖,暂停
  void onPause();

  ///返回UI控件 相当于setContentView()
  Widget buildWidget(BuildContext context);

  ///app切回到后台
  void onBackground() {
    // log("回到后台");
  }

  ///app切回到前台
  void onForeground() {
    // log("回到前台");
  }

  ///页面注销方法
  void onDestory() {
    // log("destory");
  }

  void log(String content) {
    print(getWidgetName() + "------:" + content);
  }

  //底部弹窗 强制 showBottomSheet

  //底部弹窗 非强制
  Future showBottomSheetDialog(Widget content) {
    return showModalBottomSheet(
        isScrollControlled: true,
        context: _contextBaseFunction,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
              topLeft: Radius.circular(20.0), topRight: Radius.circular(20.0)),
        ),
        builder: (builder) {
          //可以通过StatefulBuilder 改变sheet状态
          return StatefulBuilder(builder: (context1, state) {
            return SingleChildScrollView(
                child: Container(
              padding: EdgeInsets.only(
                  bottom: MediaQuery.of(context1).viewInsets.bottom),
              child: Padding(
                padding: EdgeInsets.only(top: 20),
                child: content,
              ),
            ));
          });

          // 参考demo 需要根据内容自动撑开显示区域
          // Container(
          //   height: 350.0,
          //   color: Colors.transparent,
          //   child: new Center(
          //     child: new Text("自定义区域"),
          //   ),
          // );
        });
  }

  String getWidgetName() {
    if (_contextBaseFunction == null) {
      return "";
    }
    String className = _contextBaseFunction.toString();
    if (className == null) {
      return "";
    }

    return className;
  }

  ///弹吐司 - 普通提示
  ///Fluttertoast.cancel();
  void showNormalToast(String content,
      {Toast length = Toast.LENGTH_SHORT,
      ToastGravity gravity = ToastGravity.BOTTOM,
      Color backColor = G.ToastNormalBackgroundColor,
      // Color textColor = G.buttonTextColor,
      int timeInSecForIosWeb = 2}) {
    Fluttertoast.showToast(
        msg: content,
        gravity: gravity,
        backgroundColor: backColor,
        // textColor: textColor,
        timeInSecForIosWeb: timeInSecForIosWeb);
  }

  ///弹吐司 - 正向提示
  void showRightToast(String content,
      {Toast length = Toast.LENGTH_SHORT,
      ToastGravity gravity = ToastGravity.BOTTOM,
      Color backColor = G.ToastRightBackgroundColor,
      // Color textColor = G.buttonTextColor,
      int timeInSecForIosWeb = 2}) {
    Fluttertoast.showToast(
        msg: content,
        gravity: gravity,
        backgroundColor: backColor,
        // textColor: textColor,
        timeInSecForIosWeb: timeInSecForIosWeb);
  }

  ///弹吐司 - 警告、错误提示
  void showWrongToast(String content,
      {Toast length = Toast.LENGTH_SHORT,
      ToastGravity gravity = ToastGravity.BOTTOM,
      Color backColor = G.ToastWrongBackgroundColor,
      // Color textColor = G.buttonTextColor,
      int timeInSecForIosWeb = 2}) {
    Fluttertoast.showToast(
        msg: content,
        gravity: gravity,
        backgroundColor: backColor,
        // textColor: textColor,
        timeInSecForIosWeb: timeInSecForIosWeb);
  }

  Widget _buildBottomPicker(Widget picker) {
    return Container(
      height: 216,
      padding: const EdgeInsets.only(top: 6.0),
      color: CupertinoColors.white,
      child: DefaultTextStyle(
        style: const TextStyle(
          color: CupertinoColors.black,
          fontSize: 22.0,
        ),
        child: GestureDetector(
          // Blocks taps from propagating to the modal sheet and popping.
          onTap: () {},
          child: SafeArea(
            top: false,
            child: picker,
          ),
        ),
      ),
    );
  }

  ///自定义Picker
  Widget showPickerList(
      BuildContext context,
      FixedExtentScrollController scrollController,
      List<dynamic> list,
      Widget button,
      Function callback) {
    Widget rs = GestureDetector(
      child: button,
      onTap: () async {
        await showCupertinoModalPopup<void>(
            context: context,
            builder: (BuildContext context) {
              return _buildBottomPicker(CupertinoPicker(
                magnification: 1.0, // 整体放大率
                //offAxisFraction:10.0,// 球面效果的透视系数,消失点位置
                scrollController:
                    scrollController, // 用于读取和控制当前项的FixedxtentScrollController
                itemExtent: 54, // 所以子节点 统一高度
                backgroundColor: CupertinoColors.white, // 所有子节点下面的背景颜色
                useMagnifier: true, // 是否使用放大效果
                onSelectedItemChanged: (int index) {
                  // 当正中间选项改变时的回调
                  if (_stateBaseFunction.mounted) {
                    callback(index);
                  }
                },
                children: List<Widget>.generate(list.length, (int index) {
                  return Center(
                    child: Text(
                      list[index]['name'],
                      style: TextStyle(
                          fontSize: 20, color: G.brigtTheme.primaryColor),
                    ),
                  );
                }),
              ));
            });
      },
    );
    return rs;
  }

  ///返回 状态管理组件
  _buildProviderWidget(BuildContext context) {
    if (getProvider() != null) {
      return MultiProvider(
          providers: getProvider(), child: buildWidget(context));
    } else
      return buildWidget(context);
  }

  String getClassName() {
    if (_contextBaseFunction == null) {
      return null;
    }
    String className = _contextBaseFunction.toString();
    if (className == null) {
      return null;
    }
    className = className.substring(0, className.indexOf("("));
    return className;
  }

  //可以复写
  List<SingleChildWidget> getProvider() {
    return null;
  }

  ///ListView 框架相关开始

  int curPage = 1;
  int pageNum = 20;
  ScrollController _controller = ScrollController();
  // static User loadingTag = User(name: '##下拉刷新##'); //表尾标记
  static Object loadingTag = null;
  List<Object> listData = [loadingTag];
  SlidableController slidableController;
  bool isListViewItemDel = false;
  Animation<double> _rotationAnimation;

  ///子类获取Listview ，重写相关方法自定义数据和布局。
  Widget getListView(BuildContext context) {
    Widget mainWidget;
    //默认空数据状态
    if (listData == [loadingTag] || listData.length == 1) {
      mainWidget = Center(
        child: CircularProgressIndicator(),
      );
    } else {
      // RefreshIndicator为ListView增加了下拉刷新能力，onRefresh参数传入一个方法，在下拉刷新时调用
      mainWidget = RefreshIndicator(
        child: ListView.builder(
          shrinkWrap: true,
          // physics: NeverScrollableScrollPhysics(),
          // scrollDirection: Axis.vertical,
          itemCount: listData.length,
          itemBuilder: (bcontext, index) =>
              isListViewItemDel ? _getSlidableItem(index) : _renderRow(index),
          controller: _controller,
          // physics: AlwaysScrollableScrollPhysics(),
        ),
        onRefresh: _pullToRefresh,
        // notificationPredicate: defaultScrollNotificationPredicate(),
      );
    }
    return mainWidget;
  }

  ///抽屉自动还原动画
  void handleSlideAnimationChanged(Animation<double> slideAnimation) {
    _stateBaseFunction.setState(() {
      _rotationAnimation = slideAnimation;
    });
  }

  //滑动面板项目视图
  Widget _getSlidableItem(int index) {
    return Slidable(
      key: Key(listData[index].toString()),
      controller: slidableController,
      dismissal: SlidableDismissal(
        child: SlidableDrawerDismissal(),
        onWillDismiss: (type) {
          // showToastDialog('Are sure to Delete Operation!');
          return false;
        },
        onDismissed: (actionType) {
          listViewItemFunction(index);
        },
      ),
      //滑出选项的面板 动画
      actionPane: SlidableDrawerActionPane(), //_getActionPane(item.index),
      actionExtentRatio: 0.25,
      //Item 布局
      child: _renderRow(index),
      secondaryActions: <Widget>[
        IconSlideAction(
          // caption: 'Delete',
          color: Color.fromRGBO(236, 115, 100, 1),
          // icon: Icons.delete,
          iconWidget: Text(
            '删除',
            style: TextStyle(color: Colors.white, fontSize: 16),
          ),
          onTap: () {
            listViewItemDelFunction(index);
          },
        ),
      ],
    );
  }

  setListViewItemDel(bool isOpen) {
    _stateBaseFunction.setState(() {
      isListViewItemDel = isOpen;
    });
  }

  //初始化项目结构
  Widget _renderRow(int index) {
    // index -= 1;
    // if (index > -1 && !index.isOdd) {
    //   return Padding(
    //     padding: EdgeInsets.fromLTRB(24, 0, 24, 0),
    //     child: Divider(
    //       height: 1,
    //       color: Color.fromRGBO(118, 118, 118, 1),
    //     ),
    //   );
    // }
    // index = (index + 1) ~/ 2;
    Widget itemWidget;
    if (listData[index] == loadingTag) {
      if (listData.length - 1 == pageNum * curPage) {
        //加载更多
        itemWidget = Container(
            padding: const EdgeInsets.all(16.0),
            alignment: Alignment.center,
            child: SizedBox(
                width: 24.0,
                height: 24.0,
                child: CircularProgressIndicator(strokeWidth: 2.0)));
      } else {
        //到头了
        return Container(
            alignment: Alignment.center,
            padding: EdgeInsets.all(16.0),
            child: Text(
              "----我是有底线的-----",
              style: TextStyle(color: Colors.grey),
            ));
      }
    } else {
      itemWidget = Row(
        children: <Widget>[
          Expanded(
            child: getItemWidet(index),
          ),
        ],
      );
    }

    return InkWell(
      child: Padding(
        padding: EdgeInsets.fromLTRB(24, 0, 24, 0),
        child: itemWidget,
      ),
      onTap: () {
        listViewItemFunction(index);
        //需独立context
        Slidable.of(_stateBaseFunction.context)?.renderingMode ==
                SlidableRenderingMode.none
            ? Slidable.of(_stateBaseFunction.context)?.open()
            : Slidable.of(_stateBaseFunction.context)?.close();
      },
    );
  }

  ///ListView Item 单击事件
  void listViewItemFunction(int index) {}

  void listViewItemDelFunction(int index) {
    _stateBaseFunction.setState(() {
      listData.removeAt(index);
    });
  }

  //重新刷新
  Future<Null> _pullToRefresh() async {
    // print('refresh');
    curPage = 1;
    ////下拉回调方法,方法需要有async和await关键字，没有await，刷新图标立马消失，没有async，刷新图标不会消失
    await initData(false);
    return null;
  }

  ///初始化数据
  Future<Null> initData(bool isLoadMore) async {
    // 模拟等待3秒钟
    // await Future.delayed(Duration(seconds: 3), () {
    //初始数据
    if (!isLoadMore) {
      listData = [loadingTag];
      listData.insertAll(listData.length - 1, getListData(curPage));
    } else {
      //最新新页数据
      listData.insertAll(listData.length - 1, getListData(curPage + 1));
      _stateBaseFunction.setState(() {
        curPage += 1;
      });
    }
    _stateBaseFunction.setState(() {
      listData = listData;
    });
    // });
  }

  ///数据获取方法 子类重写实现数据加载
  List<Object> getListData(int currentPageNum) {
    // if (currentPageNum == 3) {
    //   return List.generate(3,
    //       (i) => User(name: 'Name: ${i + (currentPageNum - 1) * pageNum}'));
    // } else {
    //   return List.generate(pageNum,
    //       (i) => User(name: 'Name: ${i + (currentPageNum - 1) * pageNum}'));
    // }
  }

  ///获得Item控件布局 子类重写实现自定义布局 【注意】外层已加左右边距
  Widget getItemWidet(int index) {
    // User model = listData[index];
    // return Container(
    //     height: 45,
    //     color: Colors.white,
    //     child: Center(child: Text('课程名称 - ${index} : ${model.name}')));
  }

  ///ListView 框架相关结束
}
